package com.hdu.hot100.tree;

public class lc114 {


    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public void flatten(TreeNode root)
        {
            f(root);
        }

        Info f(TreeNode root)
        {
            if (root == null) return null;
            Info l = f(root.left);
            Info r = f(root.right);
            root.left = null;
            if (l == null && r == null)
            {
                return new Info(root, root);
            }
            else if (l == null)
            {
                root.right = r.head;
                return new Info(root, r.tail);
            }
            else if (r == null)
            {
                root.right = l.head;
                return new Info(root, l.tail);
            }
            else
            {
                root.right = l.head;
                l.tail.right = r.head;
                return new Info(root, r.tail);
            }
        }

        class Info
        {
            TreeNode head;
            TreeNode tail;

            public Info(TreeNode head, TreeNode tail)
            {
                this.head = head;
                this.tail = tail;
            }
        }
    }
}
